use Map;

package MapLoader;

our $accesor = sub{
    my $obj = shift;
    my ($attrname, $newval) = (shift, shift);

    if(defined($attrname) && defined($newval)){
	$obj->{$attrname} = $newval;
    }

    return $obj->{$attrname} if(defined($attrname));
    return "";
};

sub new{
    my $class = shift;
    my $self = {};

    bless $self, $class;
    $self->MapLoader::init(@_);
    $self->init(@_) unless($class eq "MapLoader");

    return $self;
}

sub init{
    my $self =  shift;
    my $params = shift;

    if(ref $params ne "HASH"){
	$params = {};
    }

    $self->{PARAMS} = $params;
}

sub load{
    my $self = shift;
    my @invalidParams = $self->invalidParams();
    
    return undef if(scalar(@invalidParams) > 0);

    return $self->__do_generation();
}

sub __do_generation{
    # Default generator, for testing purposes only
    # Generates a map of ground tiles only, of the specified dimensions
    my $self = shift;

    my ($w, $h) = ($self->{PARAMS}->{WIDTH}, $self->{PARAMS}->{HEIGHT});


    $self->{WIDTH}  = $w;
    $self->{HEIGHT} = $h;

    my $tile;
    my @column;
    my @columns = ();

    for(my $x = 0; $x<$w; $x++){
	$column = [];
	for(my $y = 0; $y<$h; $y++){
	    # Just plain ground for now
	    $tile = Ground->spawn();
	    push(@{$column}, $tile);
	} # y
	push(@columns, $column);
    } # x

    return Map->new(\@columns);
}

sub invalidParams{
    my $self = shift;
    my @invalid = ();
    
    my ($w, $h) = ($self->{PARAMS}->{WIDTH}, $self->{PARAMS}->{HEIGHT});

    push(@invalid, "WIDTH")  unless(defined($w) && $w > 0);
    push(@invalid, "HEIGHT") unless(defined($h) && $h > 0);

    return @invalid;
}

sub params{
    my $self = shift;
    my $newParams = shift;
    return  &$accesor($self, "PARAMS", $newParams);
}

1;
